﻿using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using MESData.Infrastucture.Impement;
using MESData.Infrastucture.Interface;
using MESData.Infrastucture;
using MESData.ProductionPlan.API.AllError;
using MESData.ProductionPlan.API.Profiles;
using MESData.ProductionPlan.API.Services;

namespace MESData.ProductionPlan.API.Extensions
{
    /// <summary>
    /// 扩展方法 静态类 静态方法 this关键字
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {
            // Add services to the container.
            //注册全局异常处理
            builder.Services.AddControllers(x => x.Filters.Add<GloabIExcptionfilter>());

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //中文注释
            builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "MESData.ProductionPlan.API.xml", true));
            //注册上下文 开发环境下启用SQL日志记录
            builder.Services.AddDbContext<MyDbcontext>(x =>
            {
                x.UseMySql(builder.Configuration.GetConnectionString("db"), new MySqlServerVersion("5.7"), options =>
                {
                    // 配置连接池和并发查询选项
                    options.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                });
                // 启用服务提供程序缓存
                x.EnableServiceProviderCaching();
                // 启用敏感数据日志记录（仅在开发环境）
                if (builder.Environment.IsDevelopment())
                {
                    x.EnableSensitiveDataLogging();
                    x.LogTo(Console.WriteLine, LogLevel.Information);
                }
            });

            //配置Base模块
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            builder.Services.AddAutoMapper(typeof(UserProfile));
            AddProductionPlanServices(builder.Services);
            builder.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = builder.Configuration["Jwt:Issuer"],
                    ValidAudience = builder.Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
                };
            });

            return builder;
        }

        /// <summary>
        /// 添加生产计划相关服务
        /// </summary>
        public static IServiceCollection AddProductionPlanServices(this IServiceCollection services)
        {
            // 注册服务接口和实现
            services.AddScoped<IProductionPlanService, ProductionPlanService>();
            services.AddScoped<ISalesOrderService, SalesOrderService>();
            services.AddScoped<IItemService, ItemService>();
            services.AddScoped<IProjectService, ProjectService>();

            return services;
        }
    }
}
